package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 工具类，用于设置缓存
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 逻辑过期缓存
     *
     * @param key
     * @param value
     * @param time
     */
    public void setWithLogicExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));

    }

    public <R, ID> R queryByIdPassThrough(String key, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        //1,从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key + id);
        //2,判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //存在，返回
            R bean = JSONUtil.toBean(json, type);
            return bean;
        }
        if (json != null) {
            //缓存穿透,当查出缓存为空时，返回错误，防止查询数据库
            return null;
        }
        //3,不存在则查询数据库
        R entity = dbFallback.apply(id);
        //4，不存在则报错
        if (entity == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //5,写入缓存
        this.set(key, entity, time, unit);

        return entity;
    }

    private final static ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <R, ID> R queryByIdLogicExpire(String key, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        //1,从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key + id);
        //2,判断是否存在
        if (StrUtil.isBlank(json)) {

            return null;
        }
        //命中，反序列化json成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R o = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        //判断是否逻辑过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期，返回
            return o;
        }
        //过期，进行缓存重建
        //获取互斥锁
        String lockKey = key + id;
        boolean isLock = lock(id);
        //判断是否获取锁成功
        if (!isLock) {
            //获取锁成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R newData = dbFallback.apply(id);
                    this.setWithLogicExpire(key, newData, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(id);
                }
            });
        }


        return o;
    }

    private <ID> boolean lock(ID id) {
        Boolean setIfAbsent = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_SHOP_KEY + id, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(setIfAbsent);
    }
    private <ID> void unlock(ID id) {
        stringRedisTemplate.delete(LOCK_SHOP_KEY + id);
    }


}